package com.diary.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diary.common.result.Result;
import com.diary.server.dto.DiaryDTO;
import com.diary.server.dto.DiaryDescriptionDTO;
import com.diary.server.dto.MonthDTO;
import com.diary.server.entity.DiaryList;
import com.diary.server.service.impl.DiaryServiceImpl;
import com.diary.server.vo.CalendarVO;
import com.diary.server.vo.DiaryListVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/diary")
@Tag(name = "日记接口")
public class DiaryController {

    @Autowired
    private DiaryServiceImpl diaryService;

    @PostMapping("/save")
    @Operation(summary = "保存日记")
    public Result<String> keepDiary(@RequestBody DiaryDTO diary) {
        DiaryList diary1 = new DiaryList();
        BeanUtils.copyProperties(diary, diary1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(diary.getRecordTime(), formatter);
        log.info("时间转换成功", localDateTime);
        diary1.setRecordTime(localDateTime);
        boolean result;
        if (diary1.getId() != null && diary1.getId() > 0) {
            // 更新操作
            result = diaryService.updateById(diary1);
        } else {
            // 插入操作
            result = diaryService.save(diary1);
        }
        if (result) {
            return Result.success("保存chenggong");
        } else {
            return Result.error("保存失败");
        }
    }

    @PostMapping("/delete/{id}")
    @Operation(summary = "根据ID删除日记")
    public Result<String> deleteDiary(@PathVariable Long id) {
        try {
            // 参数校验
            if (id == null) {
                return Result.error("日记ID不能为空");
            }

            // 检查日记是否存在
            DiaryList existingDiary = diaryService.getById(id);
            if (existingDiary == null) {
                return Result.error("日记不存在");
            }

            // 执行删除操作
            boolean deleteResult = diaryService.removeById(id);

            if (deleteResult) {
                log.info("日记删除成功，ID: {}", id);
                return Result.success("日记删除成功");
            } else {
                log.error("日记删除失败，ID: {}", id);
                return Result.error("日记删除失败");
            }
        } catch (Exception e) {
            log.error("删除日记失败，ID: {}", id, e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }


    private List<DiaryListVO> changeDate(List<DiaryList> diaryList) {
        return diaryList.stream().map(diary -> {
            if (diary.getRecordTime() != null) {
                return DiaryListVO.builder()
                        .id(diary.getId())
                        .title(diary.getTitle())
                        .content(diary.getContent())
                        .recordTime(diary.getRecordTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .userId(diary.getUserId())
                        .imgs(diary.getImgs())
                        .mood(diary.getMood())
                        .textType(diary.getTextType())
                        .build();
            } else {
                return DiaryListVO.builder()
                        .id(diary.getId())
                        .title(diary.getTitle())
                        .content(diary.getContent())
                        .userId(diary.getUserId())
                        .imgs(diary.getImgs())
                        .mood(diary.getMood())
                        .textType(diary.getTextType())
                        .build();
            }
        }).toList();
    }


    @GetMapping("/list")
    @Operation(summary = "获取日记列表")
    public Result<List<DiaryListVO>> list(Long userId) {
        List<DiaryList> diaryList = diaryService.list(new QueryWrapper<DiaryList>().eq("user_id", userId));
        log.info("diaryList: {}", diaryList);
        List<DiaryListVO> diaryListVO = changeDate(diaryList);
        log.info("diaryListVO: {}", diaryListVO);
        return Result.success(diaryListVO);
    }

    @PostMapping("/byMonth")
    @Operation(summary = "获取指定月份的日记列表")
    public Result<List<CalendarVO>> getByMonth(@RequestBody MonthDTO monthDTO) {
        List<CalendarVO> calendarVOList = diaryService.getByMonth(monthDTO.getMonth());

        log.info("calendarVOList: {}", calendarVOList, monthDTO.getMonth());
        return Result.success(calendarVOList);
    }


    @GetMapping("/weekly")
    @Operation(summary = "获取指定周的日记列表")
    public Result<List<DiaryListVO>> getWeeklyDiaries(
            @RequestParam Long userId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        try {
            // 验证日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate start = LocalDate.parse(startDate, formatter);
            LocalDate end = LocalDate.parse(endDate, formatter);

            // 验证日期范围是否合理（应该是一周的范围）
            if (start.isAfter(end) || ChronoUnit.DAYS.between(start, end) > 31) {
                return Result.error("日期范围不合法");
            }

            List<DiaryList> diaries = diaryService.getWeeklyDiaries(userId, start, end);
            List<DiaryListVO> result = changeDate(diaries);

            log.info("获取周日记列表成功，用户ID: {}, 数量: {}", userId, result.size());
            return Result.success(result);
        } catch (DateTimeParseException e) {
            log.error("日期格式错误: ", e);
            return Result.error("日期格式错误，请使用 yyyy-MM-dd 格式");
        } catch (Exception e) {
            log.error("获取周日记列表失败，用户ID: {}", userId, e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @PostMapping("/updateDes")
    @Operation(summary = "更新日记描述")
    public Result<String> updateDiaryDescription(@RequestBody DiaryDescriptionDTO diaryDescriptionDTO) {
        try {
            // 参数校验
            if (diaryDescriptionDTO.getId() == null) {
                return Result.error("日记ID不能为空");
            }

            // 检查日记是否存在
            DiaryList existingDiary = diaryService.getById(diaryDescriptionDTO.getId());
            if (existingDiary == null) {
                return Result.error("日记不存在");
            }

            // 更新描述
            DiaryList diaryToUpdate = new DiaryList();
            diaryToUpdate.setId(diaryDescriptionDTO.getId());
            boolean updateResult = diaryService.updateById(diaryToUpdate);

            if (updateResult) {
                log.info("日记描述更新成功，ID: {}", diaryDescriptionDTO.getId());
                return Result.success("描述更新成功");
            } else {
                log.error("日记描述更新失败，ID: {}", diaryDescriptionDTO.getId());
                return Result.error("描述更新失败");
            }
        } catch (Exception e) {
            log.error("更新日记描述失败，ID: {}", diaryDescriptionDTO.getId(), e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }


    @GetMapping("/detailById/{id}")
    @Operation(summary = "根据日记id获取日记详情")
    public Result<DiaryListVO> getDetailById(@PathVariable Long id) {
        try {
            DiaryList diaryList = diaryService.getById(id);
            if (diaryList == null) {
                return Result.error("日记不存在");
            }

            // 修复：添加缺失的 textType 属性和空值检查
            String formattedDate = null;
            if (diaryList.getRecordTime() != null) {
                formattedDate = diaryList.getRecordTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            DiaryListVO diaryListVO = DiaryListVO.builder()
                    .id(diaryList.getId())
                    .title(diaryList.getTitle())
                    .content(diaryList.getContent())
                    .recordTime(formattedDate)
                    .userId(diaryList.getUserId())
                    .imgs(diaryList.getImgs())
                    .mood(diaryList.getMood())
                    .textType(diaryList.getTextType())
                    .build();

            return Result.success(diaryListVO);
        } catch (Exception e) {
            log.error("获取日记详情失败，id: {}", id, e);
            return Result.error("获取日记详情失败: " + e.getMessage());
        }
    }



    @GetMapping("/detail")
    @Operation(summary = "获取日记详情")
    public Result<List<DiaryListVO>> getDetailByDate(@RequestParam Long userId, @RequestParam String date) {
        try {
            // 验证日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate.parse(date, formatter);

            List<DiaryList> diaries = diaryService.getByDate(date, userId);

            return Result.success(changeDate(diaries));
        } catch (DateTimeParseException e) {
            return Result.error("日期格式错误，请使用 yyyy-MM-dd 格式");
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }
}
